package com.easylinkin.linkappapi.common.utils.message;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.easylinkin.linkappapi.alarm.entity.AlarmNotice;
import com.easylinkin.linkappapi.alarm.service.AlarmNoticeService;
import com.easylinkin.linkappapi.alarm.service.impl.AlarmNoticeServiceImpl;
import com.easylinkin.linkappapi.elasticsearch.entity.BankAlarmNotice;
import com.easylinkin.linkappapi.elasticsearch.mapper.BankAlarmNoticeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description 发送手机短信
 * @ClassName SendMessageUtil
 * @Author 徐国庆
 * @date 2020.05.15 13:39
 */
@Component
public class SendMessageUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(SendEmailUtil.class);
    @Value("${message.signName}")
    private String signName;
    @Autowired
    private IAcsClient acsClient;
    @Autowired
    private AlarmNoticeService alarmNoticeService;
    @Resource
    private BankAlarmNoticeMapper bankAlarmNoticeMapper;

    private static final Integer SUCCESS = 1;

    /**
     * 发送短信
     * @param phone 手机号
     * @param templateCode 短信模板code
     * @param templateParamStr 短信内容
     */
    public void sendSms(String phone, String templateCode, String templateParamStr) {
        SendSmsResponse sendSmsResponse = null;
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
        request.setTemplateCode(templateCode);
        request.setSignName(signName);
        request.setTemplateParam(templateParamStr);
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            LOGGER.error("getAcsResponse error:", e);
        }
        if (null != sendSmsResponse && "OK".equalsIgnoreCase(sendSmsResponse.getCode())) {
            LOGGER.info("发送短信成功:{}", request);
        }
    }

    @Async
    public void sendSmsAndSaveAlarmNotice(List<AlarmNotice> alarmNoticeList) {
        if (ObjectUtils.isEmpty(alarmNoticeList)) {
            return;
        }
        for (AlarmNotice alarmNotice : alarmNoticeList) {
            if (StringUtils.isEmpty(alarmNotice.getPhoneNumber())) {
                continue;
            }
            alarmNotice.setId(null);
            alarmNotice.setSendTime(new Date());
            alarmNotice.setMessageType(AlarmNoticeServiceImpl.PHONE_TYPE);
            alarmNotice.setMessageWay(alarmNotice.getPhoneNumber());
            SendSmsResponse sendSmsResponse = null;
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(alarmNotice.getPhoneNumber());
            request.setTemplateCode(alarmNotice.getTempletMessageContent());
            request.setSignName(signName);
            request.setTemplateParam(getParmJsonString(alarmNotice));
            if (null == acsClient) {
                continue;
            }
            try {
                sendSmsResponse = acsClient.getAcsResponse(request);
            } catch (Exception e) {
                LOGGER.error("init client  fail!{}", e.getMessage());
                LOGGER.info("阿里云发生短信失败!{}", JSON.toJSONString(sendSmsResponse));
            }
            if (null != sendSmsResponse && "OK".equalsIgnoreCase(sendSmsResponse.getCode())) {
                alarmNotice.setStatus(SUCCESS);
                alarmNoticeService.save(alarmNotice);
            }
        }
    }


    @Async
    public void sendBankAlarmSms(BankAlarmNotice bankAlarmNotice) {
        if (StringUtils.isEmpty(bankAlarmNotice.getPhoneNumber())) {
            return;
        }
        LOGGER.info("发送短信的贷后管理告警日志入库" + bankAlarmNotice.toString());
        bankAlarmNoticeMapper.insert(bankAlarmNotice);
        SendSmsResponse sendSmsResponse = null;
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(bankAlarmNotice.getPhoneNumber());
        request.setTemplateCode(bankAlarmNotice.getTempletMessageContent());
        request.setSignName(signName);
        request.setTemplateParam(BankAlarmNotice.getBankParmJsonString(bankAlarmNotice));
        if (null == acsClient) {
            return;
        }
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            LOGGER.error("initi client  fail!",e);
        }
        if (null != sendSmsResponse && "OK".equalsIgnoreCase(sendSmsResponse.getCode())) {
            bankAlarmNotice.setStatus(SUCCESS);
            bankAlarmNoticeMapper.updateById(bankAlarmNotice);
        }
    }


    @Async
    public void sendVerificationCode(String phone, String randomNo) {
        SendSmsResponse sendSmsResponse;
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
        SendSmsRequest request = new SendSmsRequest();
        request.setPhoneNumbers(phone);
//        request.setTemplateCode("SMS_126855007");
        request.setTemplateCode("SMS_249900069");
        request.setSignName(signName);
        request.setTemplateParam(getVerificationCodeJsonString(randomNo));
        if (null == acsClient) {
            return;
        }
        try {
            sendSmsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
            LOGGER.error("initi client  fail!", e);
        }
    }

    static String getVerificationCodeJsonString(String randomNo) {
        JSONObject param = new JSONObject();
        param.put("code", randomNo);
        return param.toString();
    }

    static String getParmJsonString(AlarmNotice alarmNotice) {
        JSONObject param = new JSONObject();
        param.put("areaPath", alarmNotice.getAreaPath());
        param.put("deviceType", alarmNotice.getDeviceType());
        param.put("content", alarmNotice.getContent());
        return param.toString();
    }


}

